package screen;

import java.util.Vector;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import font.BitmapFont;

import animation.FlyText;
import animation.Smoke;

import service.GlobalService;
import utilities.CRes;
import utilities.GameResource;
import utilities.TileMap;

import main.GameCanvas;
import main.NuoiThuMidlet;
import model.Animal;
import model.Command;
import model.IAction;
import model.PlayerInfo;
import model.Position;

public class FightingScr extends PlayGameScr {

	private Command m_throwDiceCmd;
	private int m_iTime;
	private int m_interval;
	private int[] m_arrPoint;
	private int[] m_arrHealth;
	private int m_iTickEyes = CRes.random(20, 40);
	private boolean m_bEyes = false;
	private short m_sNumber = 0;
	private int m_iTickWings = 0;
	private short m_sStatusWings = 0;
	private boolean m_bStarActionDice = false;
	private int m_iGameTick = 0;
	private int deltaX = 0,deltaY = 0;
	private boolean m_bEndGame = false;
	private int m_iWhoWin;
	private boolean m_bisCloser = false;
	private boolean m_bWinnerAction = false;
	private byte m_bWhoAttack = 0;
	private byte m_bWhoStand = 0;
	private int m_iGoAttack = 0;
	private int m_iDistance ;
	private boolean m_bLying = false;
	private int m_iWhoPlayFirst;
	private int m_hGameCanvas;
	private Image m_imgBackRoundGame;
	static FightingScr instance;

    public static FightingScr gI() {
        if (instance == null) {
            instance = new FightingScr(2);
        }
        return instance;
    }
    
    public static void clean(){
		if(instance != null){
			instance.m_arrHealth = null;
			instance.m_arrPoint = null;
			instance.m_imgBackRoundGame = null;
			instance.m_imgBackground = null;
			instance.m_arrChatContent = null;
			instance.m_arrPlayers = null;
			instance.m_arrPos = null;
		}
		instance = null;		
	}
    
    private static String[] m_sWinnerChat ={
    	"HeHe, thắng rồi",
    	"Hận đời vô đối!",
    	"Hay không bằng hên",
    	"Chết mày chưa",
    	"Cho mày chừa",
    	"Quá dễ dàng",
    	"Đối thủ quá kém",
    	"Thắng rùi!!!",
    	"Đầu óc ngu si, tứ chi phát triển"
    };
    private static String[] m_sCloserChat = {
    	"Đau quá !",
    	"Chết tui rồi",
    	"Hên ghê !",
    	"Hix hix",
    	"Hu hu",
    	"Xui quá !",
    	"Nản thiệt",
    	"Vãi quá",
    	"...",
    	"Nhường 1 lượt đó",
    	"Hay đó",
    	"Ac thiệt !",
    	"Rõ nản",
    	"Thúi hẻo rùi",
    	"Xúi quẩy"
    };
	public FightingScr(int maxPlayer) {
		super(maxPlayer);
		// TODO Auto-generated constructor stub
		m_bIsDisplayAnimal = true;
		
		m_arrPos[0] = new Position(10, GameCanvas.h - 150);
		m_arrPos[0].anchor = 0;
		
		m_arrPos[1] = new Position(GameCanvas.w - 70, m_arrPos[0].y);
		m_arrPos[1].anchor = 1;
		
		m_throwDiceCmd = new Command("Đổ xúc xắc", new IAction() {
			public void perform() {
				// TODO Auto-generated method stub
				GlobalService.gI().doThrowDice(m_iRoomID, m_iBoardID);
				m_bStarActionDice = true;
				m_iTime = m_interval;
		}
		});
		
		m_arrPoint = new int[2];
		m_arrHealth = new int[2];
		
		m_hGameCanvas = GameCanvas.h;
		
		///paint 
		TileMap.instance.loadMap(TileMap.FIGHTING_MAP);
		m_imgBackRoundGame = Image.createImage(GameCanvas.w, GameCanvas.h);
		Graphics g = m_imgBackRoundGame.getGraphics();
		
		int left = 0;
		int width = GameCanvas.w;
		int height = GameCanvas.h;
		
		g.setClip(left, left, width, height + 10);
		g.setColor(0x8be2ff);
        g.fillRect(0, 0, width, height);
		
        int hMap = height - TileMap.m_iHeightTile * 7;
        int i = left;
		int yTmp = hMap - GameResource.instance.imgScreenLogin.getHeight() + 48;
		int tmpW = GameResource.instance.imgScreenLogin.getWidth();
        for(i = left; i < width; i += tmpW){
        	g.drawImage(GameResource.instance.imgScreenLogin, i, yTmp, Graphics.LEFT | Graphics.TOP);
        }     
        
        int wTile = TileMap.m_iHeightTile * 7;
        for(i = left; i < width; i += wTile){
        	TileMap.instance.paintMap(g, i, hMap);
        }
		
		int wToGate = width/2 - (GameResource.instance.imgGate.getWidth()>>1);
		int wFrance = GameResource.instance.imgFance.getWidth();
		hMap += 10;
		i = width/2 - (GameResource.instance.imgGate.getWidth()>>1) + 5;
        while(i >= left){
        	i -= wFrance;
        	g.drawImage(GameResource.instance.imgFance, i, hMap, Graphics.LEFT | Graphics.TOP);
        }
        i = width/2 + (GameResource.instance.imgGate.getWidth()>>1) - 5;
        while(i <= width){
        	g.drawImage(GameResource.instance.imgFance, i, hMap, Graphics.LEFT | Graphics.TOP);
        	i += wFrance;
        }
        g.drawImage(GameResource.instance.imgGate, wToGate, hMap+wFrance, Graphics.LEFT | Graphics.BOTTOM);
        
        BitmapFont.drawBoldFont(g, "Đấu trường", width/2, hMap+wFrance-GameResource.instance.imgGate.getHeight()+17, 0xffffff, Graphics.VCENTER|Graphics.HCENTER);
	}

	private void earthQuake(int anchor){
		if(deltaX != 0 && deltaY != 0){
			if(deltaX < 0)
				anchor = -anchor;
			deltaX -= 2*deltaX - anchor;
			
			if(deltaY < 0)
				anchor = -anchor;
			deltaY -= 2*deltaY - anchor;
		}
	}
	
	public void switchToMe(byte roomID1, byte boardID, Vector vtPlayers,
			int ownerID, int money) {
		// TODO Auto-generated method stub
		super.switchToMe(roomID1, boardID, vtPlayers, ownerID, money);
	}

	public void onStartGame(int whoPlayFirst, short interval, short health0, short health1) {
		// TODO Auto-generated method stub
		GameCanvas.endDlg();
		
		m_arrPoint[0] = m_arrPoint[1] = 0;
		m_arrHealth[0] = health0;
		m_arrHealth[1] = health1;
		
		startGame();
		
		m_iPlayerInTurn = whoPlayFirst;
		m_iCurrentTime = 101;
		if(whoPlayFirst == NuoiThuMidlet.m_myPlayerInfo.m_iId){
			m_cmdCenter = m_throwDiceCmd;
		}
		else
			m_cmdCenter = null;
		
		m_interval = interval;
		m_iTime = m_interval;
		
		
		m_bisCloser = false;
		m_bEndGame = false;
		m_bStarActionDice = false;
		m_bLying = false;
		m_iWhoPlay = findPlayerPos(whoPlayFirst);
	
		m_iWhoPlay = (m_iWhoPlay == 0 )? 1 : 0;
		m_iWhoPlayFirst = m_iWhoPlay;
		
		if(m_iWhoPlayFirst == m_iWhoPlay && m_arrPlayers[m_iWhoPlay].m_iId == NuoiThuMidlet.m_myPlayerInfo.m_iId){
			m_bStarActionDice = true;
		}
	}
	
	public void paint(Graphics g){
		g.translate(-g.getTranslateX(), -g.getTranslateY());
		g.setClip(0, 0, GameCanvas.w, GameCanvas.h);
		
		g.drawImage(m_imgBackRoundGame, deltaX, deltaY, 0);
		int hMap = m_hGameCanvas - TileMap.m_iHeightTile * 7 + GameResource.instance.imgFance.getHeight() - GameResource.instance.imgGate.getHeight()- 5; 
		PaintPopup.paintDice(g, m_sNumber, GameCanvas.hw, hMap, m_sStatusWings, m_bEyes);
		
		if(isPlaying()){
			int posPlayer = 0;
			for(int i = 0; i < m_iMaxPlayer; i++){
				if(m_arrPlayers[i].m_iId == -1)
					continue;
				
				posPlayer = i;
				//paint avatar
				m_arrPlayers[i].paintAvatarInBoard(g, m_arrPos[posPlayer].x, 5, 75 , 40);
				
				//paint animal's health
				PaintPopup.paintHealtyBar(g, m_arrPos[posPlayer].x+25, 40, m_arrPlayers[i].m_defaultPet.animalInfo.m_sHealth, m_arrHealth[i], m_arrPlayers[i].m_defaultPet.m_iBonusHealth);
			
				//paint animal
				if(m_bWinnerAction && i == m_bWhoAttack){
					m_arrPlayers[i].m_defaultPet.paintAction(g, 1, Animal.RUN, deltaX + m_iGoAttack + m_arrPos[posPlayer].x + ((m_arrPos[posPlayer].anchor == 1)? 30: 0), deltaY + m_hGameCanvas - 50, m_arrPos[posPlayer].anchor);
					
				}
				else
				{
					if(m_bisCloser){
						if(posPlayer == m_bWhoStand)
							m_arrPlayers[i].m_defaultPet.paintAction(g, 1, Animal.SLEEP, deltaX + m_arrPos[posPlayer].x + ((m_arrPos[posPlayer].anchor == 1)? 30: 0), deltaY + m_hGameCanvas - 50, m_arrPos[posPlayer].anchor);
						else
							m_arrPlayers[i].m_defaultPet.paintAction(g, 1, Animal.STAND, deltaX + m_arrPos[posPlayer].x + ((m_arrPos[posPlayer].anchor == 1)? 30: 0), deltaY + m_hGameCanvas - 50, m_arrPos[posPlayer].anchor);
					}
					else{
						if(posPlayer == m_bWhoStand && m_bLying)
							m_arrPlayers[i].m_defaultPet.paintAction(g, 1, Animal.SLEEP, deltaX + m_arrPos[posPlayer].x + ((m_arrPos[posPlayer].anchor == 1)? 30: 0), deltaY + m_hGameCanvas - 50, m_arrPos[posPlayer].anchor);
						else
							m_arrPlayers[i].m_defaultPet.paintAction(g, 1, Animal.STAND, deltaX + m_arrPos[posPlayer].x + ((m_arrPos[posPlayer].anchor == 1)? 30: 0), deltaY + m_hGameCanvas - 50, m_arrPos[posPlayer].anchor);
					}
				}
				PlayerInfo p = m_arrPlayers[i];
				if(p.m_defaultPet.m_bEnableChat){
					p.m_defaultPet.m_position.anchor = m_arrPos[i].anchor;
					
					if(posPlayer == m_bWhoAttack)
						p.m_defaultPet.m_position.x = m_iGoAttack+m_arrPos[i].x + ((m_arrPos[i].anchor == 1)? 30: 0);
					else
						p.m_defaultPet.m_position.x = m_arrPos[i].x + ((m_arrPos[i].anchor == 1)? 30: 0);
					
					p.m_defaultPet.m_position.y = m_hGameCanvas - 50;
					p.m_defaultPet.paintBoxChatAnimals(g);
				}
				
				//paint score
				BitmapFont.drawOutlinedString(g, m_arrPoint[posPlayer] + "",  m_arrPos[posPlayer].x+25, 45, 0x3a001e, 0);
				//paint time
				if(posPlayer != m_iWhoPlay && !m_bEndGame){
					PaintPopup.paintBoxClock(g, m_arrPos[posPlayer].x, 38, "" + m_iTime);
				}
			}
			
				
		}
		super.paint(g);
	}
	
	public void update(){
		///
		earthQuake(1);
		///
		m_iTickEyes --;
		if(m_iTickEyes < 2){
			m_bEyes = true;
		}
		if(m_iTickEyes < 0){
			m_bEyes = false;
			m_iTickEyes = CRes.random(20, 40);
		}
		m_iTickWings ++ ;
		if(m_iTickWings >2){
			m_sStatusWings ++;
			m_sStatusWings %= 4;
			m_iTickWings = 0; 
		}
		
		if(m_bStarActionDice){
			m_iGameTick ++;
			m_sNumber = (short) (m_iGameTick%6 + 1);
		}
		////////winner action
		updateWinnner(5);
		
		
		///
		if(isPlaying()){
    		m_iCurrentTime++;
    		
    		if(m_iCurrentTime % 20 == 0 && m_iTime > 0)
    			m_iTime--;
    			
    		if(m_iCurrentTime == 100){
    			
    			
    			setNextPlayer(m_iPlayerInTurn);
    			m_iTime = m_interval;
    		}
    		
    		int i;
    		for(i = 0 ; i <m_iMaxPlayer; i++){
    			PlayerInfo p = m_arrPlayers[i];
    			p.m_defaultPet.updateChat();
    		}
    		
    		
			if(m_bisCloser){
				m_iGameTick ++;
				if(m_iGameTick%20 == 0)
					m_sNumber --;

				if(m_sNumber <= 0){
					stopGame();
					GameCanvas.endDlg();
				}
			}
    		
    	}
		
		super.update();
	}

	public void updateWinnner(int speed){
		if(m_bWinnerAction){
			if(m_bLying){
				m_arrPlayers[m_bWhoAttack].m_defaultPet.changeFrameRunPet();
				
				
				if(m_arrPos[m_bWhoStand].x > m_arrPos[m_bWhoAttack].x){
					m_iGoAttack -= speed;
				}
				
				else{
					m_iGoAttack += speed;
				}
				
				
				if(Math.abs(m_iGoAttack) <= 0){
					setFinishStep();
				}
			}
			else{
				m_arrPlayers[m_bWhoAttack].m_defaultPet.changeFrameRunPet();
				
				
				if(m_arrPos[m_bWhoStand].x > m_arrPos[m_bWhoAttack].x){
					m_iGoAttack += speed;
				}
				
				else{
					m_iGoAttack -= speed;
				}
				
				if( Math.abs(m_iGoAttack) >= m_iDistance){
					
					if(m_arrPos[m_bWhoAttack].anchor == 0)
						m_arrPos[m_bWhoAttack].anchor = 1;
					else
						m_arrPos[m_bWhoAttack].anchor = 0;
					m_bLying = true;
					
					////////
					deltaX = CRes.random(2, 5);
					deltaY = CRes.random(2, 5);
					
					
					int delX;
					if(m_bWhoStand == 0)
						delX = 15;
					else
						delX = 0;
					
					int wAnimal = 0;
					if(m_bWhoStand == 0){
						wAnimal = m_arrPlayers[m_bWhoStand].m_defaultPet.animalInfo.m_bodyPart[1].m_iW;
					}
					
					int i;
					for(i = 0; i < 10; i++){
						int a = CRes.random(2);
						int b = CRes.random(2);
						if(a == 0 && a == b)
							a = 1;
						byte c = 3;
						if(i>4)
							c = 2;
						if(i>7)
							c = 1;
						Smoke stun = new Smoke();
						stun.startEffect(m_arrPos[m_bWhoStand].x + delX + wAnimal, GameCanvas.h-70, a, b, c, Smoke.STAR);
					}
					Smoke stun = new Smoke();
					stun.startEffect(m_arrPos[m_bWhoStand].x + delX + wAnimal, GameCanvas.h-70, 0, 0, (byte) 2, Smoke.STUN);
					
					FlyText text = new FlyText();
					text.startEffect("-1 giọt", m_arrPos[m_bWhoStand].x + delX + wAnimal, GameCanvas.h-70, 0x00ff00, 0x000000);
					
					///chat animal
					PlayerInfo p = findPlayer(m_arrPlayers[m_bWhoStand].m_iId); 
					p.m_defaultPet.chat(m_sCloserChat[CRes.random(0, m_sCloserChat.length)]);
					p.m_defaultPet.m_iTimeEndChatAnimal = 50;
					////
					
					if(m_bEndGame){
						m_bStarActionDice = false;
						m_bisCloser = true;
						p = findPlayer(m_arrPlayers[m_bWhoAttack].m_iId); 
						p.m_defaultPet.chat(m_sWinnerChat[CRes.random(0, m_sWinnerChat.length)]);
						p.m_defaultPet.m_iTimeEndChatAnimal = 50;
						endGame();
					}
				}
			}
			
		}
		
	}
	
	public void setFinishStep(){
		///point and dice
		m_arrPoint[0] = 0;
		m_arrPoint[1] = 0;
		
		if(!m_bisCloser){
			m_sNumber = 0;
		}
		
		m_bWinnerAction = false;
		m_iGoAttack = 0;
		m_bLying = false;
		
		m_arrPos[m_bWhoAttack].anchor = m_bWhoAttack;
		
		
	}
	
	public void setNextPlayer(int playerId){
		m_iPlayerInTurn = playerId;
		
		if(playerId == NuoiThuMidlet.m_myPlayerInfo.m_iId){
			setFinishStep();
			m_iTime = m_interval;
			m_cmdCenter = m_throwDiceCmd;
		}
		else{
			m_cmdCenter = null;
		}
		if(m_bEndGame){
			m_cmdCenter = null;
		}
	}

	public void onEndGame(int whoWin, boolean howOutGame) {
		// TODO Auto-generated method stub
		
		m_bEndGame = true;
		m_iWhoWin = whoWin;
		m_sNumber = 5;
		m_iGameTick = 0;
		
		if(howOutGame){
			endGame();
		}
	}
	
	private void endGame(){
		flyMoney();
		
		
		m_bStarActionDice = false ;
		m_cmdCenter = null;
		String m_str= "";
		if(m_iWhoWin == NuoiThuMidlet.m_myPlayerInfo.m_iId){
			if(m_iMoney > 0){
				int money = (m_iMoney*2 - m_iMoney/5);
				m_str = "Bạn đã chiến thắng!\nBạn được: "+money;
			}
			else
				m_str = "Bạn đã chiến thắng!";
		}
		else{
			if(m_iMoney > 0){
				m_str = "Bạn đã thua!\nBạn bị trừ: "+m_iMoney;
			}
			else{
				m_str = "Bạn đã thua!";
			}
		}
		//PlayerInfo p = findPlayer(m_iWhoWin);
		GameCanvas.startOK(m_str, new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				stopGame();
				GameCanvas.endDlg();
			}
		});
		
		for(int i = 0; i < m_arrPlayers.length; i++){
			if(m_arrPlayers[i] != null && m_arrPlayers[i].m_iId != m_iOwnerID)
				m_arrPlayers[i].isReady = false;
		}
		
	}
	
	private int m_iWhoPlay;
	
	public void onThrowDice(int whoPlay, byte point, int nextPlay,
			boolean isNewPlay, int posAttack) {
		// TODO Auto-generated method stub
		int pos = findPlayerPos(whoPlay);
		m_arrPoint[pos] = point;
		
		////
		m_sNumber = point;
		m_iGameTick = 0;
		m_bStarActionDice = false;
		m_iTime = m_interval;
		m_iWhoPlay = pos;
		////
		if(posAttack != -1){
			//nguoi thang tan cong
			m_bWinnerAction = true;
			m_bWhoAttack = (byte) posAttack;
			m_bWhoStand = 0;
			if(m_bWhoAttack == m_bWhoStand)
				m_bWhoStand = 1;
			
			
			int tmpW = m_arrPlayers[m_bWhoStand].m_defaultPet.animalInfo.m_iW[1];
			m_iDistance = Math.abs(m_arrPos[0].x - m_arrPos[1].x) - tmpW;
			
			m_iTime = 0;
			//tru mau cua nguoi thua
			m_arrHealth[1 - posAttack]--;
			//set next player
			m_iCurrentTime = 0;
			m_iPlayerInTurn = nextPlay;
			
			//clear center command
			m_cmdCenter = null;
		}
		else
		{
			m_iPlayerInTurn = nextPlay;
			m_iCurrentTime = 101;
			if(nextPlay == NuoiThuMidlet.m_myPlayerInfo.m_iId){
				m_cmdCenter = m_throwDiceCmd;
			}
			else
				m_cmdCenter = null;
			
			if(isNewPlay){
				FlyText text = new FlyText();
				text.startEffect("Hòa", GameCanvas.hw, GameCanvas.hh, 0x00ff00, 0x000000);
			}
		}
	}
	
	public void onChatFromMe(String text) {
		// TODO Auto-generated method stub
		super.onChatFromMe(text);
	}
	
	int m_iMoneyp, m_iMoneyv;
	String m_sMoneyText;
	public void onBonusMoney(int playerId, int value, String text) {
		// TODO Auto-generated method stub
		if(!m_bEndGame){
			super.onBonusMoney(playerId, value, text);
		}
		else{
			m_iMoneyp = playerId;
			m_iMoneyv = value;
			m_sMoneyText = text;
		}
	}
	
	
	private void flyMoney(){
		
		int pos = findPlayerPos(m_iMoneyp);
		PlayerInfo p = findPlayer(m_iMoneyp);
		FlyText f;
		if(m_iMoneyp == NuoiThuMidlet.m_myPlayerInfo.m_iId && m_iMoneyp == m_iWhoWin){
			
			f = new FlyText();
			f.startEffect(m_sMoneyText, m_arrPos[pos].x, 100, 0xffff00, 0x000000);
			
			f = new FlyText();
			f.startEffect("" + m_iMoneyv, m_arrPos[pos].x, 110, 0xffff00, 0x000000);
		}
		if(m_iMoneyp == NuoiThuMidlet.m_myPlayerInfo.m_iId){
			NuoiThuMidlet.m_myPlayerInfo.setMoney(NuoiThuMidlet.m_myPlayerInfo.getMoney(0) + m_iMoneyv, 0);
		}
		if(p != null)
			p.setMoney(p.getMoney(0) + m_iMoneyv, 0);
	}
}
